/**
 * 认证相关的工具函数
 */

const TOKEN_KEY = 'mailspeed_token';
const USER_INFO_KEY = 'mailspeed_user_info';

// Token管理
export function getToken(): string | null {
  return localStorage.getItem(TOKEN_KEY);
}

export function setToken(token: string): void {
  localStorage.setItem(TOKEN_KEY, token);
}

export function removeToken(): void {
  localStorage.removeItem(TOKEN_KEY);
}

// 用户信息管理
export function getUserInfo(): any {
  const userInfo = localStorage.getItem(USER_INFO_KEY);
  return userInfo ? JSON.parse(userInfo) : null;
}

export function setUserInfo(userInfo: any): void {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
}

export function removeUserInfo(): void {
  localStorage.removeItem(USER_INFO_KEY);
}

// 清除所有认证信息
export function clearAuth(): void {
  removeToken();
  removeUserInfo();
}

// 检查是否已登录
export function isLoggedIn(): boolean {
  return !!getToken();
}

// 检查是否是管理员
export function isAdmin(): boolean {
  const userInfo = getUserInfo();
  return userInfo?.role === 'admin';
}

// 检查用户角色
export function hasRole(role: string): boolean {
  const userInfo = getUserInfo();
  return userInfo?.role === role;
}

// 检查是否有权限
export function hasPermission(requiredRoles: string[]): boolean {
  const userInfo = getUserInfo();
  if (!userInfo) return false;
  return requiredRoles.includes(userInfo.role);
}
